<template>
	<view>
		<view class="uni-header">
			<uni-stat-breadcrumb class="uni-stat-breadcrumb-on-phone" />
			<view class="uni-group">
				<button class="uni-button" v-show="jindu != ''" type="primary" size="mini">{{jindu}}</button>

				<button @click="xiazai" type="primary" size="mini">{{zi}}</button>
				<button class="uni-button" type="primary" size="mini"
					@click="navigateTo('./add')">{{ $t('common.button.add') }}</button>
				<button class="uni-button" type="warn" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">{{ $t('common.button.batchDelete') }}</button>
				<input class="uni-search" type="text" v-model="query" @confirm="search"
					:placeholder="$t('common.placeholder.query')" />
				<button class="uni-button hide-on-phone" type="default" size="mini"
					@click="search">{{ $t('common.button.search') }}</button>
				<!-- 导入文件 -->
				<button class="uni-button" type="primary" @click="chooseFile" size="mini">导入</button>
				<download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData"
					:type="exportExcel.type" :name="exportExcel.filename">
					<button class="uni-button" type="primary" size="mini">{{$t('common.button.exportExcel')}}</button>
				</download-excel>
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" :collection="collectionList" :options="options" :where="where" page-data="replace"
				:orderby="dbOrderBy" :getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
				v-slot:default="{ data, pagination, loading, error, options }" @load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe
					type="selection" @selection-change="selectionChange" style="max-height: 710px;">
					<uni-tr>
						<uni-th align="center" width="50">序号</uni-th>
						<uni-th align="center" width="150">货品编码</uni-th>
						<!-- <uni-th align="center" width="100">供应商</uni-th> -->
						<uni-th align="center" width="220">货品名称</uni-th>
						<uni-th align="center" width="180">规格型号</uni-th>
						<uni-th align="center" width="80">计量单位</uni-th>
						<uni-th align="center" width="220">产品中文描述</uni-th>
						<uni-th align="center" width="80">货位</uni-th>
						<uni-th align="center" width="80">MOQ</uni-th>
						<uni-th align="center" width="80">清洗类型</uni-th>
						<uni-th align="center" width="80">清洗单价</uni-th>
						<uni-th align="center" width="80">版本号</uni-th>
						<uni-th align="center" width="80">交货期</uni-th>
						<uni-th align="center" width="100">未清洗</uni-th>
						<uni-th align="center" width="100">已清洗</uni-th>
						<uni-th align="center" width="100">总库存</uni-th>
						<uni-th align="center" width="80">未税单价</uni-th>
						<uni-th align="center" width="80">附件</uni-th>
						<uni-th align="center" width="120">添加时间</uni-th>
						<uni-th align="center" width="140">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item, index) in data" :key="index">
						<uni-td align="center">{{ index + 1 }}</uni-td>
						<uni-td align="center">{{ item.goods_sn }}</uni-td>
						<uni-td align="center">{{ item.name }}</uni-td>
						<uni-td align="center">{{ item.type }}</uni-td>
						<uni-td align="center">{{ item.danwei }}</uni-td>
						<uni-td align="center">{{ item.goods_desc }}</uni-td>
						<uni-td align="center">{{ item.position }}</uni-td>
						<uni-td align="center">{{ item.moq || 0 }}</uni-td>
						<uni-td align="center">{{ item.qx_type || 0 }}</uni-td>
						<uni-td align="center">{{ item.qx_price> 0 ? item.qx_price.toFixed(2) : 0 }}</uni-td>
						<uni-td align="center">{{ item.all_price || 0 }}</uni-td>
						<uni-td align="center">{{ item.jh_time }}</uni-td>
						<uni-td align="center">{{ item.wqx_count || 0 }}</uni-td>
						<uni-td align="center">{{ item.yqx_count || 0 }}</uni-td>
						<uni-td align="center">{{ item.remain_count || 0 }}</uni-td> 
						<uni-td align="center">{{ item.shop_price}}</uni-td>
						<uni-td align="center"><text class="blue cu_po"
								@click="openFj(item.goods_fj)">附件</text></uni-td>
						<uni-td align="center">{{ $formatDate(item.add_date) }}</uni-td>
						<uni-td align="center">
							<view class="uni-group">
								<text class="green cu_po" @click="open(item)">+库存</text>
								<text class="blue cu_po" style="margin-left: 10px;"
									@click="navigateTo('./add?id=' + item._id, false)">修改</text>
								<text class="red cu_po" style="margin-left: 10px;"
									@click="confirmDelete(item._id)">删除</text>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>

		</view>
		<view class="text-center dialog">
			<!-- 输入框示例 -->
			<uni-popup ref="popup" type="dialog" :mask-click="false">
				<view class="popup-all bg-w">
					<view>
						<view class="" style="display:flex;margin-bottom: 15px;">
							<text>单价：</text> <input class="uni-input" v-model="priceArr.price" type="number"
								placeholder="请输入单价" />
						</view>
						<view class="" style="display:flex">
							<text>数量：</text><input class="uni-input" v-model="priceArr.num" type="number"
								placeholder="请输入数量" />
						</view>
					</view>
					<view class="t-c mar-t-15 ">
						<button class="mini-btn mar-r-15" type="primary" @click="dialogInputConfirm"
							size="mini">确定</button>
						<button class="mini-btn" @click="close" type="default" size="mini">取消</button>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import * as XLSX from 'xlsx'
	//库存列表
	const db = uniCloud.database();
	const dbCollectionName = 'opendb-mall-goods';
	// 表查询配置
	const dbOrderBy = 'add_date desc'; // 排序字段
	const dbSearchFields = ['goods_sn', 'seller_note', 'type', 'keywords', 'name', 'goods_desc',
	'position']; // 支持模糊搜索的字段列表
	// 分页配置
	const pageCurrent = 1;

	export default {
		data() {
			return {
				jindu: '',
				collectionList: "opendb-mall-goods",
				selectedIndexs: [],
				query: '',
				zi: "显示所有数据",
				where: '',
				dbOrderBy: dbOrderBy,
				exportExcelData: [],
				exportExcel: {
					"filename": "货品.xls",
					"type": "xls",
					"fields": {
						"货品编码": "goods_sn",
						"货品名称": "name",
						"规格型号": "type",
						"计量单位": "danwei",
						"产品中文描述": "goods_desc",
						"货位": "position",
						"MOQ": 'moq',
						"清洗类型": "qx_type",
						"清洗单价": "qx_price",
						"版本号": "all_price",
						"未清洗": "wqx_count",
						"已清洗": "yqx_count",
						"总库存": "remain_count",
						"未税单价": "shop_price",
						"成本单价": "price",
						"交货期": "jh_time",
						"添加时间": "add_date",

					}
				},
				options: {
					pageSize: 10,
					pageCurrent
				},
				cheRow: {},
				priceArr: {},
				columns: [{
						label: 'Name',
						key: 'name'
					},
					{
						label: 'Age',
						key: 'age'
					},
					{
						label: 'Gender',
						key: 'gender'
					}
				],
				tableData: [] // 存储导入的数据
			};
		},
		onLoad() {},
		methods: {
			dateTime(timestamp) {
				console.log();
				const date = new Date(timestamp); // 创建一个 Date 对象
				return date.toLocaleString(); // 转换为本地日期时间字符串
			},
			onqueryload(data) {
				data.forEach(item => {
					item.add_date = this.dateTime(item.add_date)
				})
				this.exportExcelData = data
			},
			close() {
				this.$refs.popup.close()
			},
			xiazai() {
				if (this.zi == '显示所有数据') {
					this.zi = "还原"
					this.options.pageSize = 1000
					this.getData()

				} else {
					this.zi = "显示所有数据"
					this.options.pageSize = 10
				}

			},
			async getData() {
				let limit = 1000; // 每次查询的数量
				let offset = 0; // 偏移量	
				let res = await db.collection("opendb-mall-goods").count();
				let total = res.result.total
				console.log(total);
				let promiseArr = []; //promise列表
				do {
					let promise = db.collection('opendb-mall-goods').skip(offset).limit(limit)
						.get(); //将查询数据的结果赋值给变量promise
					promiseArr.push(promise) //将返回结果push到promiseArr
					offset += limit;
				} while (offset < total);

				let arr = await Promise.all(promiseArr) //通过.all统一同时执行请求
				console.log(arr);
				let result = arr.map(item => {
					return item.result.data
				}).flat(); //返回的是每个的数据对象，将需要的res.data返回，并flat将二维数组变为一维数组
				console.log(result, 1234);
				this.exportExcelData = result
			},
			// 增加库存
			async dialogInputConfirm() {
				let data = await db.collection('opendb-mall-goods').doc(this.cheRow._id).field('remain_count').get()
				console.log(this.cheRow.price, this.priceArr.price);
				let nowPrice = (this.cheRow.price + this.priceArr.price * 1) / 2
				let remain_count = data.result.data[0].remain_count + this.priceArr.num * 1

				uniCloud.callFunction({
					name: 'add-kucun',
					data: {
						id: this.cheRow._id,
						price: nowPrice,
						remain_count: remain_count,
						num: this.priceArr.num * 1
					}
				}).then(res => {
					console.log(res);
					if (res.result.code === 200) {
						this.$refs.popup.close()
						uni.showModal({
							content: '库存更新成功',
							showCancel: false
						});
						setTimeout(() => uni.navigateBack(), 500);
						// 通过 eventChannel 发送 'refreshData' 事件，通知其他页面刷新数据
						this.getOpenerEventChannel().emit('refreshData');
					} else {
						uni.showModal({
							content: '库存更新失败',
							showCancel: false
						});
						this.$refs.popup.close()
						console.log('库存更新失败:', res.result.msg);
					}
				}).catch(err => {
					console.error('调用云函数失败', err);
				});



			},
			// 创建一个下载多个附件的函数
			downloadMultipleFiles(fileUrls) {
				fileUrls.forEach(function(url, index) {
					setTimeout(function() {
						const a = document.createElement('a');
						a.href = url;
						a.download = ''; // 触发下载并使用默认的文件名
						a.style.display = 'none'; // 隐藏元素
						document.body.appendChild(a);
						a.click(); // 模拟点击下载
						document.body.removeChild(a); // 移除元素
					}, index * 1000); // 每个下载请求间隔 1 秒
				});
			},
			//下载附件
			openFj(item) {
				if (item && item.length > 0) {
					let url = []
					item.forEach(res => {
						url.push(res.url)
					})
					this.downloadMultipleFiles(url)
				} else {
					uni.showModal({
						content: '暂无附件',
						showCancel: false
					});
				}

			},
			open(e) {
				this.cheRow = e
				this.priceArr = {}
				// 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
				this.$refs.popup.open('center')
			},
			chooseFile() {
				// 调用文件选择器
				uni.chooseFile({
					extension: ['.xlsx', '.xls'],
					success: (res) => {
						const file = res.tempFiles[0];
						console.log(res, 111);
						this.readExcel(file);
					}
				});
			},
			timeCz(excelDate) {
				console.log(excelDate);
				const timestamp = (excelDate - 25569) * 86400 * 1000 - 28843000; // 25569 是 Excel 日期基准，86400 是一天的秒数
				const date = new Date(timestamp); // 转换为 JavaScript 日期对象
				return new Date(date).getTime()

			},
			readExcel(file) {
				const reader = new FileReader();
				reader.onload = (e) => {
					const binaryString = e.target.result;
					const wb = XLSX.read(binaryString, {
						type: 'binary'
					});
					const ws = wb.Sheets[wb.SheetNames[0]];
					const data = XLSX.utils.sheet_to_json(ws);

					// 处理并存储数据
					this.tableData = data.map(item => ({
						goods_sn: item['货品编码'],
						name: item['货品名称'],
						type: item['规格型号'],
						danwei: item['计量单位'],
						goods_desc: item['产品中文描述'],
						position: item['货位'],
						moq: item['MOQ'],
						qx_type: item['清洗类型'],
						qx_price: item['清洗单价'],
						all_price: item['版本号'],
						wqx_count: item['未清洗'],
						yqx_count: item['已清洗'],
						remain_count: item['总库存'],
						shop_price: item['未税单价'],
						price: item['成本单价'],
						jh_time: item['交货期'],
					}));
					console.log(this.tableData, 99);
					// this.tableData = this.tableData.slice(1)
					uni.showLoading({
						title: "导入中" + this.jindu
					});

					// 定义一个函数，接收一个批次的数据，并执行插入操作
					const insertBatch = (batch) => {
						const promises = batch.map(item => {

							if (isNaN(item['goods_sn'])) {
								item['goods_sn'] = String(item['goods_sn']); // 如果是非数字，则转换为字符串
							} else {
								item['goods_sn'] = item['goods_sn'].toString(); // 如果是数字，转换为字符串
							}

							// 处理 jh_time，检查是否为空且是数字
							let jhTimeValue = item['jh_time'];
							if (item['jh_time'] !== null && item['jh_time'] !== undefined && !
								isNaN(item[
									'jh_time'])) {
								jhTimeValue = item['jh_time'].toString(); // 转换为字符串
							}


							// 处理 position，检查是否为空且是数字
							let positionValue = item['position'];
							if (item['position'] !== null && item['position'] !== undefined && !isNaN(item[
									'position'])) {
								positionValue = item['position'].toString(); // 转换为字符串
							}

							// 处理 position，检查是否为空且是数字
							let all_priceValue = item['all_price'];
							if (item['all_price'] !== null && item['all_price'] !== undefined && !isNaN(
									item['all_price'])) {
								all_priceValue = item['all_price'].toString(); // 转换为字符串
							}

							// 处理 moq，将空值或无效值转为数字
							let moqValue = 0; // 默认为0，或根据需要选择其他默认值
							if (item['moq'] !== null && item['moq'] !== undefined && item[
									'moq'] !== '') {
								moqValue = !isNaN(item['moq']) ? Number(item['moq']) :
									0; // 如果是有效数字则转换为数字
							}


							return db.collection(dbCollectionName).add({
								goods_sn: String(item['goods_sn']),
								name: item['name'],
								type: String(item['type']),
								sj_count: item['sj_count'],
								goods_desc: String(item['goods_desc']),
								position: positionValue,
								price: Number(item['price']),
								shop_price: Number(item['shop_price']),
								jh_time: jhTimeValue,
								qx_price: Number(item['qx_price']),
								danwei: item['danwei'],
								moq: moqValue,
								qx_type: item['qx_type'],
								yqx_count: Number(item['yqx_count']),
								wqx_count: Number(item['wqx_count']),
								remain_count: Number(item['remain_count']),
								add_date: Date.now(),
								unit_id: "6476e69209e2989198d4db61",
								all_price: all_priceValue,
							}).catch(error => {
								console.error("Database insert failed:", error);
								return Promise.reject(error);
							});
						});

						return Promise.all(promises);
					};

					// 将所有数据分批处理，每批次大小根据需要调整
					const batchSize = 10; // 每批请求大小
					const batches = [];
					for (let i = 0; i < this.tableData.length; i += batchSize) {
						batches.push(this.tableData.slice(i, i + batchSize));
					}

					// 逐批请求
					let currentBatchIndex = 0;
					const processBatches = async () => {
						const totalBatches = batches.length; // 获取总批次数量
						try {
							for (let i = currentBatchIndex; i < batches.length; i++) {
								await insertBatch(batches[i]); // 等待当前批次处理完成
								this.jindu = `${i + 1}/${totalBatches}`
								currentBatchIndex = i + 1; // 更新当前批次索引
							}
							uni.showToast({
								title: '新增成功',
							});
							setTimeout(() => uni.navigateBack(), 500);
							this.getOpenerEventChannel().emit('refreshData');
						} catch (err) {
							uni.showModal({
								content: err.message || '请求服务失败',
								showCancel: false
							});
						} finally {
							uni.hideLoading();
						}
					};

					// 开始处理批次
					processBatches();


				};


				reader.readAsBinaryString(file);
			},
			getWhere() {
				const query = this.query.trim();
				if (!query) {
					return '';
				}
				let queryRe;
				try {
					queryRe = new RegExp(query, 'i');
				} catch (err) {
					uni.showToast({
						title: '请勿输入\等不满足正则格式的符号',
						icon: 'none'
					});
					return;
				}
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ');
			},
			search() {
				const newWhere = this.getWhere();
				const isSameWhere = newWhere === this.where;
				this.where = newWhere;
				if (isSameWhere) {
					// 相同条件时，手动强制刷新
					this.loadData();
				}
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				});
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0;
				this.$refs.table.clearSelection();
				this.$refs.udb.loadData({
					current: e.current
				});
			},
			navigateTo(url) {
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData();
						}
					}
				});
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList;
				console.log(dataList);
				return this.selectedIndexs.map(i => dataList[i]._id);
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: res => {
						this.$refs.table.clearSelection();
					}
				});
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index;
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: res => {
						this.$refs.table.clearSelection();
					}
				});
			}
		}
	};
</script>
<style>
	.uni-table-tr {

		& th:last-child,
		& td:last-child {
			background-color: white;
		}
	}

	.popup-all {
		padding: 15px
	}
</style>